<template>
  <div>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="4">
          <el-card class="leftBox" shadow="never" :body-style="{padding: '0px'}">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item title="按类型查看" name="1">
                <div class="selectArea">
                  <el-tree
                    ref="treeone"
                    :data="optionsType"
                    :expand-on-click-node="false"
                    node-key="mat_type_id"
                    :default-expanded-keys="[1]"
                    :props="{ children: 'children', label: 'mat_type_name', type: 'mat_type' }"
                    @node-click="handleTypeClick">
                  </el-tree>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-col>
        <el-col :span="20">
            <div class="clearfix" v-if="crud.props.searchToggle">
              <!-- 搜索 -->
              <el-input v-model="query.name" clearable placeholder="输入节目名称" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
              <rrOperation />
            </div>
            <crudOperation :permission="permission" />
            <!--表单组件-->
            <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="670px">
              <el-form ref="form" inline :model="form" :rules="rules" label-width="85px">
                <el-row :gutter="15">
                  <el-col :span="12">
                    <el-form-item label="节目代码" prop="pgm_id">
                      <el-input v-model="form.pgm_id" class="elInputS"  disabled />
                    </el-form-item>
                    <el-form-item label="节目名称" prop="pgm_name">
                      <el-input v-model="form.pgm_name" class="elInputS"  />
                    </el-form-item>
                    <el-form-item label="节目类型" prop="pgm_type">
                      <el-cascader
                        v-model="form.pgm_type"
                        :options="optionsType[0].children"
                        :props="{emitPath: false, value: 'mat_type_id', label: 'mat_type_name'}"
                        placeholder="请选择节目类型"
                        :show-all-levels="false"
                        style="margin-left: 0;"
                        class="elInputS">
                      </el-cascader>
                    </el-form-item>
                    <el-form-item label="节目属性" prop="pgm_attr">
                      <el-select v-model="form.pgm_attr" class="elInputS" placeholder="请选择节目属性">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_Attr" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label=" " prop="if_sign">
                      <el-checkbox label="转播" v-model="form.if_sign" :true-label="1" :false-label="0"></el-checkbox>
                    </el-form-item>
                    <el-form-item label="总集数" prop="pgm_id">
                      <el-input v-model="form.sum_num" class="elInputS" :disabled="form.pgm_attr === 1 ? true : false" />
                    </el-form-item>
                    <el-form-item label="单集长度" prop="pgm_len">
                      <time-picker v-model="form.pgm_len" format="HH:ii:ss" class="elInputS" />
                    </el-form-item>
                    <el-form-item label="创建人" prop="creator">
                      <el-input v-model="form.truename" disabled class="elInputS" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="声道选择">
                      <el-select v-model="form.audio_chan" class="elInputS">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_audio_chan" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="语言">
                      <el-select v-model="form.pgm_language" class="elInputS">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_language" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="需要遮挡">
                      <el-select v-model="form.need_cover" class="elInputS">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_need_cover" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="宽银幕">
                      <el-select v-model="form.wide_screen" class="elInputS">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_wide_screen" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="节目来源">
                      <el-select v-model="form.pgm_source" class="elInputS">
                        <el-option  v-for="(item, index) in pgmInfoConfig.pgm_source" :label="item.label" :value="item.id"  :key="index"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="主演">
                      <el-input v-model="form.leader_actor" class="elInputS" />
                    </el-form-item>
                    <el-form-item label="首播日期">
                      <el-date-picker
                        class="elInputS"
                        value-format="yyyy-MM-dd"
                        style="width: 100%;"
                        v-model="form.start_date"
                        type="date"
                        placeholder="选择日期">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item label="创建日期" prop="remark">
                      <el-input v-model="form.create_time" disabled class="elInputS" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" style="width: 530px;" />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="crud.cancelCU">取消</el-button>
                <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
              </div>
            </el-dialog>
            <!-- 列表区域 -->
            <el-table
              height="47vh"
              ref="table"
              highlight-current-row
              @current-change="rowsCurrentChange"
              v-loading="crud.loading"
              lazy
              :data="crud.data"
              border
              stripe
              @select="crud.selectChange"
              @select-all="crud.selectAllChange"
              @selection-change="crud.selectionChangeHandler"
              @sort-change="handleSortEvent"
              style="width: 100%;">
              <el-table-column :selectable="checkboxT" type="selection" width="55" />
              <el-table-column prop="pgm_id" label="代码" sortable="custom"></el-table-column>
              <el-table-column prop="pgm_name" label="名称" sortable="custom" width="120px" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pgm_type" label="类型" sortable="custom" width="120px" show-overflow-tooltip>
                <template v-slot="scope">
                  {{scope.row.pgm_type_name}}
                </template>
              </el-table-column>
              <el-table-column prop="pgm_attr" label="节目属性">
                <template v-slot="scope">
                  {{findValLabel(scope.row.pgm_attr, pgmInfoConfig.pgm_Attr, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="sum_num" label="总集数" sortable="custom" width="90px">
                <template v-slot="scope">
                  {{scope.row.pgm_attr === 2 ? scope.row.sum_num : '--'}}
                </template>
              </el-table-column>
              <el-table-column prop="pgm_len" label="单集长度" sortable="custom" width="100px">
                <template v-slot="scope">
                  <time-picker inputType="readonly" format="HH:ii:ss" v-model="scope.row.pgm_len" />
                </template>
              </el-table-column>
              <el-table-column prop="creator" label="创建人">
                <template v-slot="scope">
                  {{scope.row.truename}}
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="创建日期" sortable="custom" width="120px">
                <template v-slot="scope">
                  {{scope.row.create_time | subTimeDate}}
                </template>
              </el-table-column>
              <el-table-column prop="audio_chan" label="声道选择" width="120px">
                <template v-slot="scope">
                  {{findValLabel(scope.row.audio_chan, pgmInfoConfig.pgm_audio_chan, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="need_cover" label="需要遮挡">
                <template v-slot="scope">
                  {{findValLabel(scope.row.need_cover, pgmInfoConfig.pgm_need_cover, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="pgm_source" label="节目来源">
                <template v-slot="scope">
                  {{findValLabel(scope.row.pgm_source, pgmInfoConfig.pgm_source, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="pgm_language" label="语言">
                <template v-slot="scope">
                  {{findValLabel(scope.row.pgm_language, pgmInfoConfig.pgm_language, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="wide_screen" label="宽银幕">
                <template v-slot="scope">
                  {{findValLabel(scope.row.wide_screen, pgmInfoConfig.pgm_wide_screen, 'id') || ''}}
                </template>
              </el-table-column>
              <el-table-column prop="leader_actor" label="主演"></el-table-column>
              <el-table-column prop="start_date" label="首播日期" width="100px"></el-table-column>
              <el-table-column label="操作" fixed="right" width="120">
                <template slot-scope="scope">
                  <udOperation
                    :data="scope.row"
                    :permission="permission"
                    :disabled-dle="scope.row.id === 1"
                    msg="确定删除吗,此操作不能撤销！"
                  />
                </template>
              </el-table-column>
            </el-table>
            <!--分页组件-->
            <pagination />
            <el-row :gutter="15" class="footCard">
              <el-col :span="20">
                <el-table
                  ref="tabletwo"
                  highlight-current-row
                  @current-change="rowsplayCurrentChange"
                  @selection-change="handleSelectionChange"
                  lazy
                  height="21vh"
                  :data="playList"
                  v-loading="playloading"
                  border
                  stripe
                  style="width: 100%;">
                  <!-- <el-table-column :selectable="checkboxT" type="selection" width="55" /> -->
                 <el-table-column
                    label="序号"
                    type="index"
                    width="60">
                  </el-table-column>
                  <!-- <el-table-column prop="play_id" label="序号"></el-table-column> -->
                  <el-table-column prop="dev_name" label="首播">
                    <template v-slot="scope">
                      <span v-if="scope.row.first_flag === 0" style="color:red">X</span>
                      <span v-else style="color:green">✔</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="channel_name" label="频道"></el-table-column>
                  <el-table-column prop="dev_model_name" label="一直有效">
                    <template v-slot="scope">
                      <span v-if="scope.row.all_avail === 0" style="color:red">X</span>
                      <span v-else style="color:green">✔</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="s_play_date" label="开始时间"></el-table-column>
                  <el-table-column prop="e_play_date" label="结束时间"></el-table-column>
                </el-table>
              </el-col>
              <el-col :span="4">
                <div class="detailOpera" style="display: flex; flex-direction: column;align-items: center;margin-top: 15px;">
                  <el-button style="margin-left: 10px;width: 100px;" type="primary" icon="el-icon-plus" v-permission="permission.add" :disabled="rowscurrent === null" @click="toAdd">新增</el-button>
                  <el-button style="width: 100px;" icon="el-icon-edit" @click="toEdit" v-permission="permission.edit" :disabled="playcurrentRow === null">编辑</el-button>
                  <el-button style="width: 100px;" icon="el-icon-delete" @click="toDel" v-permission="permission.del" type="danger" :disabled="playcurrentRow === null">删除</el-button>
                  <el-button style="width: 100px;" type="success" icon="el-icon-video-play" @click="playsetVisible = true" v-permission="permission.del" :disabled="playcurrentRow === null">播放安排</el-button>
                </div>
              </el-col>
            </el-row>
            <el-dialog
              append-to-body
              :close-on-click-modal="false"
              :before-close="handlecancelCU"
              :visible.sync="playDialog.status.cu > 0"
              :title="playDialog.status.title"
              width="450px">
              <el-form ref="playform" inline :model="playform" :rules="playformrules" label-width="85px">
                <el-form-item label="频道" prop="channel_id">
                  <el-select v-model="playform.channel_id" placeholder="请选择">
                    <el-option
                      v-for="item in channelList"
                      :key="item.id"
                      :label="item.channel_name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label=" " prop="first_flag">
                  <el-checkbox class="elInputS" label="首播" v-model="playform.first_flag" :true-label="1" :false-label="0"></el-checkbox>
                </el-form-item>
                <el-form-item label=" ">
                  <el-checkbox class="elInputS" label="一直有效" v-model="playform.all_avail" :true-label="1" :false-label="0"></el-checkbox>
                </el-form-item>
                <el-form-item label="开始时间">
                  <el-date-picker
                    class="elInputS"
                    value-format="yyyy-MM-dd"
                    style="width: 100%;"
                    v-model="playform.s_play_date"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="e_play_date">
                  <el-date-picker
                    :disabled="playform.all_avail === 1 ? true : false"
                    class="elInputS"
                    value-format="yyyy-MM-dd"
                    style="width: 100%;"
                    v-model="playform.e_play_date"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="handlecancelCU">取消</el-button>
                <el-button :loading="playDialog.status.cu === 3" type="primary" @click="handlesubmitCU">确认</el-button>
              </div>
            </el-dialog>
            <!-- 播放安排组件 -->
            <play-setting
              v-if="playsetVisible"
              :innerVisible="playsetVisible"
              :scopeRow="playcurrentRow"
              @close="playsetVisible = false">
            </play-setting>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@/components/Crud/crud'
import crudDevice, { playList, playListAdd, playListEdit, playListDel } from '@/api/pgmmanage/pgmlib.js' // 引入当前栏目的后端api
import { matTlist } from '@/api/material/mattype.js'
import commonMethods from '@/utils/commonMethods.js'
import { dateFormat } from '@/utils/commonFun.js'
import { pgmInfoConfig } from '@/sysconfig.js' // 引入节目库系统配置
import { channelMenuList } from '@/api/channel/channel.js' // 频道列表接口

// 引入已封装好的增删改查相关组件
import rrOperation from '@/components/Crud/RrOperation.vue' // 搜索查询组件
import crudOperation from '@/components/Crud/CrudOperation.vue' // 列表顶部功能区域组件
import pagination from '@/components/Crud/Pagination.vue' // 分页组件
import udOperation from '@/components/Crud/UD.operation' // 列表操作列组件
import playSetting from '@/components/playSettingComponents.vue' // 节目播放信息组件

// 配置表单字段， 并设置字段初始值
const defaultForm = {
  pgm_id: 0,
  pgm_name: null,
  pgm_attr: 1,
  pgm_type: null,
  if_sign: 0,
  pgm_len: 0,
  sum_num: 0,
  creator: '系统管理员',
  create_time: null,
  remark: '',
  audio_chan: null,
  need_cover: null,
  pgm_source: null,
  pgm_language: null,
  wide_screen: null,
  leader_actor: null,
  start_date: null
}
export default {
  name: 'Pgmlib',
  components: { rrOperation, crudOperation, pagination, udOperation, playSetting },
  cruds() { // 该方法，返回当前组件配置初始化后的实例对象
    return CRUD({ idField: 'pgm_id', title: '节目库管理', url: 'pgmmanage/pgmlib', crudMethod: { ...crudDevice }, sort: ['pgm_id,desc'] })
  },
  mixins: [presenter(), header(), form(defaultForm), crud(), commonMethods],
  filters: {
    subTimeDate: function(value) {
      if (value !== null && value.length > 10) {
        return value.substr(0, 10)
      }
      return value
    }
  },
  watch: {
    'crud.data'() {
      this.playList = []
    }
  },
  data() {
    // 验证邮箱规则
    var checkPgmLen = (rule, value, callback) => {
      if (value > 0) {
        return callback()
      } else {
        return callback(new Error('请输入节目长度!'))
      }
    }

    var checkfirstPlay = (rule, value, callback) => {
      if (this.playList.length > 0) {
        if (this.playList.length === 1 && (this.$refs.playform.model.play_id === this.playList[0].play_id)) {
          return value > 0 ? callback() : callback(new Error('至少设置为一条首播信息!'))
        } else {
          return callback()
        }
      } else {
        if (value > 0) {
          callback()
        } else {
          return callback(new Error('请设置为首播信息!'))
        }
      }
    }

    var checkExitTime = (rule, value, callback) => {
      if (value < this.playform.s_play_date) {
        return callback(new Error('结束时间不能小于开始时间!'))
      }

      return callback()
      // console.log(value, this.playform.s_play_date)
    }

    return {
      /* 设置页面权限 */
      permission: {
        add: ['admin', 'pgmlib::add'],
        edit: ['admin', 'pgmlib::edit'],
        del: ['admin', 'pgmlib::del']
      },
      rules: {
        pgm_name: [
          { required: true, message: '节目名称不能为空', trigger: 'blur' }
        ],
        pgm_type: [
          { required: true, message: '节目类型不能为空', trigger: 'blur' }
        ],
        pgm_len: [
          { validator: checkPgmLen, trigger: 'blur' } // 检查节目长度
        ]
      }, // 表单验证规则
      activeName: '1',
      optionsType: [
        { children: [] }
      ],
      pgmInfoConfig, // 节目库系统配置
      // 设备型号配置数组
      deviceFlag: [
        { id: '1', label: 'linux服务器' }
      ],
      channelList: [], // 频道列表
      rowscurrent: null,
      handleCheckboxRows: [],
      playList: [],
      playloading: false,
      playDialog: {
        status: {
          cu: 0,
          title: '新增节目播放信息'
        }
      },
      playform: {},
      playformrules: {
        channel_id: [
          { required: true, message: '请先选择频道信息！', trigger: 'blur' }
        ],
        first_flag: [
          { validator: checkfirstPlay, trigger: 'blur' } // 检查是否为首播
        ],
        e_play_date: [
          { validator: checkExitTime, trigger: 'blur' }
        ]
      },

      playcurrentRow: null, // 播放安排选中行
      playsetVisible: false // 播放安排弹窗显示隐藏
    }
  },
  async created() {
    // console.log(this.pgmInfoConfig)
    this.query.type = []
    this.crud.optShow.download = false // 隐藏 导出按钮
    // 获取节目类型菜单
    this.getmatTypeList()
    this.channelList = await channelMenuList()
    console.log(this.channelList)
  },
  mounted() {
    this.crud.updateProp('searchToggle', false)
  },
  methods: {
    getmatTypeList() {
      matTlist().then(res => {
        if (res.status !== 200) {
          console.log('获取失败')
        }
        this.optionsType = res.data.data[0].children.filter(item => {
          if (item.mat_type_name !== '广告') {
            return item
          }
        })
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== false
    },
    // 按类型查看
    handleTypeClick(data, node, el) {
      if (this.$refs.treeone.currentNode !== null) {
        this.$refs.treeone.currentNode.$el.setAttribute('class', 'el-tree-node')
      }
      el.$el.setAttribute('class', 'el-tree-node is-current is-focusable') // 设置选中
      if (data.mat_type_id === undefined) {
        this.query.type = 'all'
      } else {
        this.query.type = this.findNodeChildValArr(data, 'mat_type_id', []).join(',')
      }
      this.crud.toQuery()
    },
    // 排序点击
    handleSortEvent(sort) {
      const sortArr = { descending: 'desc', ascending: 'asc' }
      if (sort.order !== null) {
        this.crud.sort = sort.prop + ',' + sortArr[sort.order]
      } else {
        this.crud.sort = ''
      }
      this.crud.toQuery()
    },
    // 单元行选中事件
    rowsCurrentChange(rows) {
      this.rowscurrent = rows
      this.getrowsplaylist(rows)
    },
    getrowsplaylist(rows) {
      if (rows === null) return
      if (typeof rows.pgm_id === 'number' && rows.pgm_id > 0) {
        this.playloading = true
        playList({ pgm_id: rows.pgm_id }).then(res => {
          if (res.status !== 200) {
            this.$message.error('获取失败!')
          }
          this.playloading = false
          this.playList = res.data.data.list
          this.$nextTick(() => {
            this.$refs.tabletwo.setCurrentRow(this.playList[this.playList.length - 1])
          })
        })
      }
    },
    rowsplayCurrentChange(rows) {
      this.playcurrentRow = rows
      this.$nextTick(() => {
        if (this.playcurrentRow !== null && this.playcurrentRow !== undefined) {
          this.playcurrentRow = Object.assign(this.playcurrentRow || {}, this.rowscurrent)
        }
      })
      // console.log(rows, 'abc')
    },
    // 新增编辑前回调方法
    [CRUD.HOOK.beforeToCU](crud, form) {
      if (typeof form.pgm_type_name !== 'undefined') {
        delete form.pgm_type_name
      }
      console.log(form)
    },
    // 删除之后回调方法
    [CRUD.HOOK.afterDelete](crud, form) {
      console.log('删除成功')
      this.playList = [] // 清空播放信息列表
    },
    handlecancelCU() {
      this.playDialog.status.cu = 0
      console.log('cancle')
    },
    handlesubmitCU() {
      this.$refs.playform.validate(async valid => {
        if (!valid) return
        if (this.playDialog.status.cu === 1) {
          this.playDialog.status.cu = 3
          playListAdd(this.playform).then(res => {
            if (res.status !== 200) {
              this.$message.error('新增失败!')
            }
            this.playDialog.status.cu = 0 // 关闭弹窗
            this.getrowsplaylist(this.rowscurrent)
            return this.$message.success('新增成功!')
          }).catch(err => {
            this.playDialog.status.cu = 1
            console.log(err)
          })
        } else {
          this.playDialog.status.cu = 3
          playListEdit(this.playform).then(res => {
            if (res.status !== 200) {
              this.$message.error('编辑失败!')
            }
            this.playDialog.status.cu = 0 // 关闭弹窗
            this.getrowsplaylist(this.rowscurrent)
            return this.$message.success('编辑成功!')
          }).catch(err => {
            this.playDialog.status.cu = 2
            console.log(err)
          })
        }
      })
    },
    resetPlayForm(pgm_id) {
      const defaultform = {
        pgm_id,
        all_avail: 0,
        channel_id: null,
        first_flag: 0,
        s_play_date: dateFormat(new Date(), 'ymd'),
        e_play_date: dateFormat(new Date(), 'ymd')
      }
      this.playform = defaultform
    },
    handleSelectionChange(select) {
      this.handleCheckboxRows = select || []
    },
    toAdd() {
      if (this.rowscurrent === null) {
        return
      }
      this.resetPlayForm(this.rowscurrent.pgm_id)
      this.playDialog.status.cu = 1
      this.playDialog.status.title = '新增节目播放信息'
    },
    toEdit() {
      console.log(this.handleCheckboxRows)
      if (this.playcurrentRow === null) {
        return false
      }
      this.playDialog.status.cu = 2
      this.playDialog.status.title = '编辑节目播放信息'
      this.playform = JSON.parse(JSON.stringify(this.playcurrentRow))
      console.log(this.playform)
    },
    async toDel() {
      const confirmresult = await this.$confirm('是否确定删除当前节目 `' + this.rowscurrent.pgm_name + '` 的播放信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }

      if (this.playcurrentRow === null) {
        return false
      }

      playListDel(this.playcurrentRow).then(res => {
        if (res.status !== 200) {
          this.$message.error('删除失败!')
        }
        this.getrowsplaylist(this.rowscurrent)
        return this.$message.success('删除成功！')
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .operator {
    float: right;
    display: inline-block;
    margin-left: 20px;
  }
  .detailOpera .el-button {
    margin-top: 15px;
  }
  .leftBox {
    height: 81vh;
    background-color: rgba(222, 223, 230, 0.6);
  }
  .footCard {
    border:  1px solid rgba(222, 223, 230, 1);
    margin-top: 10px;
  }
</style>
